

import  AppDispatcher from '../dispatcher/AppDispatcher';

import SocialConstants '../constants/SocialConstants';
import JSONUtil '../utils/jsonutil';

var SocialActions  = {
	filterTweets:function(event){
		AppDispatcher.dispatcher({
			type:SocialConstants.FILTER_BY_TWEETS,
			showTweets:event.target.checked
		});
	},
	filterReddits: function (event) {
		AppDispatcher.dispatch({
			type: SocialConstants.FILTER_BY_REDDITS,
			showReddits: event.target.checked
		});
	},
	syncTweets: function (json) {
		AppDispatcher.dispatch({
			type: SocialConstants.SYNC_TWEETS,
			tweets: json.map((tweet) => {
				return Object.assign(tweet, {type: 'tweet'})
			}),
			receivedAt: Date.now()
			}
		);
	},
	syncReddits: function (json) {
		AppDispatcher.dispatch({
			type: SocialConstants.SYNC_REDDITS,
			reddits: json.data.children.map((child) => {
				return Object.assign(child.data, {type: 'reddit'})
			}),
			receivedAt: Date.now()
		});
	},
	fetchTweets: function (username) {
		fetch('/tweets.json?username=${username}')
		.then(JSONUtil.parseJSON)
		.then(json => SocialActions.syncTweets(json)).catch(JSONUtil.
		handleParseException)
	},
	fetchReddits: function (topic) {
		fetch('https://www.reddit.com/r/${topic}.json')
		.then(JSONUtil.parseJSON)
		.then(json => SocialActions.syncReddits(json)).catch(JSONUtil.
		handleParseException)
	}
}

export default SocialActions


